package com.why.whyojcodesandbox.utils;

import com.why.whyojcodesandbox.model.dto.ExecuteMessage;
import org.springframework.util.StopWatch;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ProcessUtils {
    public static ExecuteMessage runProcessAndGetMessage(Process runProcess, String opName) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ExecuteMessage executeMessage = new ExecuteMessage();
        try {
        int exitValue = runProcess.waitFor();
        executeMessage.setExitValue(runProcess.exitValue());
        StringBuilder compileOutput = new StringBuilder();
        StringBuilder compileErrorOutput = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
        String compileOutputLine;
        while ((compileOutputLine = bufferedReader.readLine()) != null) {
            compileOutput.append(compileOutputLine);
            executeMessage.setMessage(compileOutput.toString());
        }
        if (exitValue == 0) {
            System.out.println(opName + "成功");
        } else {
            System.out.println(opName + "失败");
            bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getErrorStream()));
            while ((compileOutputLine = bufferedReader.readLine()) != null) {
                compileErrorOutput.append(compileOutputLine);
            }
            executeMessage.setErrorMessage(compileErrorOutput.toString());
        }
    } catch (Exception e) {
    e.printStackTrace();
    }
        stopWatch.stop();
        executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
        return executeMessage;
    }

}
